package com.pai4j.ugc.messaegqueue.service;


import com.google.common.collect.Lists;
import com.pai4j.common.enums.AccountRelationTypeEnum;
import com.pai4j.common.enums.MessageTypeEnum;
import com.pai4j.common.enums.messagequeue.MessageBroadChannelEnum;
import com.pai4j.common.service.messagequeue.producer.MessageQueueProducer;
import com.pai4j.common.util.DateUtils;
import com.pai4j.domain.vo.request.mess.MessageNotifyVO;
import com.pai4j.domain.vo.response.UserBaseResponseInfoVO;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.ugc.service.AccountService;
import com.pai4j.ugc.service.chain.*;
import com.pai4j.ugc.service.moment.MomentTimeLineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service
public class MomentPublishConsumeService {

    @Autowired
    private MomentImageHandler momentImageHandler;
    @Autowired
    private MomentVideoHandler momentVideoHandler;
    @Autowired
    private MomentLinkHandler momentLinkHandler;
    @Autowired
    private MomentReviewHandler momentReviewHandler;
    @Autowired
    private MomentRefreshHandler momentRefreshHandler;
    @Autowired
    private MomentIpAddressHandler momentIpAddressHandler;
    @Autowired
    private MomentCommentHandler momentCommentHandler;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MomentTimeLineService momentTimeLineService;
    @Autowired
    private MessageQueueProducer<MessageNotifyVO, Long> notificationMessageQueueProducer;



    /**
     * 写扩散策略，内容审核质量分超过5，朋友可见，反之仅发帖子人自己可见（降级策略）
     * ps: 基于score可以实现分段策略，比如小红数作品评分在：
     * 10 ~ 40 丢初级流量池
     * 41 ~ 80 丢千人流量池
     * 81 ~ 100 丢万人流量池
     */
    private static final int WRITE_TIME_LINE_SCORE = 5;
    
    /**
     * 动态发布后置处理
     *
     * @param dto 动态VO对象
     *
     * @author: CYM-pai
     * @date: 2025/01/04 12:15
     */
    public void consume(MomentVO dto) throws Exception {
        try {
            log.info("开始处理动态发布后置任务: momentId={}, author={}", dto.getId(), dto.getAuthor());

            /**
             * 后置动态数据处理链（应用责任链设计模式）：
             *
             * 1. 图片媒体资源信息提取
             * 2. 视频媒体资源信息提取
             * 3. 连接解析
             * 4. ip归属地解析
             * 5. 大模型内容审核
             * 6. 刷新/修改动态状态
             * ……
             */
            MomentPublishHandlerChain chain = new MomentPublishHandlerChain();
            chain.addHandler(Lists.newArrayList(momentImageHandler,
                                                momentVideoHandler,
                                                momentLinkHandler,
                                                momentIpAddressHandler,
                                                momentReviewHandler,
                                                momentCommentHandler,
                                                momentRefreshHandler)).handle(dto, chain);

            /**
             * 写扩散（把当前动态写入到所有粉丝时间线DB、Redis）
             */
            Integer reviewScore = dto.getReviewScore();
            // 大模型内容审核结果质量分
            boolean writeFriends = reviewScore != null && reviewScore > WRITE_TIME_LINE_SCORE;
            momentTimeLineService.addTimeLine(dto.getAuthor(), dto.getId(), dto.getPublishTime(), writeFriends);

            /**
             * 发送动态通知消息
             * 只有通过审核且允许写入朋友时间线的动态才发送通知
             */
            if (writeFriends) {
                sendMomentNotification(dto);
            }

            log.info("动态发布后置任务处理完成: momentId={}, author={}, writeFriends={}",
                    dto.getId(), dto.getAuthor(), writeFriends);

        } catch (Exception e) {
            log.error("动态发布后置任务处理失败: momentId={}, author={}", dto.getId(), dto.getAuthor(), e);
            throw e;
        }
    }

    /**
     * 发送动态通知消息
     * 通知关注该用户的粉丝有新动态发布
     *
     * @param momentVO 动态VO对象
     *
     * @author: CYM-pai
     * @date: 2025/08/04 12:20
     */
    private void sendMomentNotification(MomentVO momentVO) {
        try {
            // 获取作者的所有粉丝
            Set<String> followers = accountService.getAllSubscriberByAccount(
                    momentVO.getAuthor(), AccountRelationTypeEnum.USER_USER);

            if (CollectionUtils.isEmpty(followers)) {
                log.info("用户无粉丝，跳过动态通知发送: author={}, momentId={}",
                        momentVO.getAuthor(), momentVO.getId());
                return;
            }

            // 获取作者名称
            UserBaseResponseInfoVO authorInfo = accountService.accountInfo(momentVO.getAuthor());
            // 生成动态内容摘要（用于通知显示）
            String contentSummary = generateContentSummary(authorInfo.getUserName());

            // 批量发送通知消息
            for (String followerId : followers) {
                MessageNotifyVO messageNotifyVO = new MessageNotifyVO();
                messageNotifyVO.setSenderId(momentVO.getAuthor());
                messageNotifyVO.setReceiverId(followerId);
                messageNotifyVO.setSender(authorInfo);
                messageNotifyVO.setTime(DateUtils.getCurrentTimeMillis());
                messageNotifyVO.setType(MessageTypeEnum.MOMENT_NOTIFICATION.getType());
                messageNotifyVO.setContent(contentSummary);

                //发送到动态通知队列
                try {
                    notificationMessageQueueProducer.broadSend(MessageBroadChannelEnum.QUEUE_MOMENT_NOTIFICATION, messageNotifyVO);
                    } catch (Exception redisException) {
                        log.error("发送动态通知失败: momentId={}, receiverId={}",
                                momentVO.getId(), messageNotifyVO.getReceiverId(), redisException);
                    }
                }
            log.info("动态通知消息发送完成: author={}, momentId={}, followers count={}",
                    momentVO.getAuthor(), momentVO.getId(), followers.size());

        } catch (Exception e) {
            log.error("发送动态通知消息失败: author={}, momentId={}",
                    momentVO.getAuthor(), momentVO.getId(), e);
            // 通知发送失败不影响主业务流程，只记录日志
        }
    }

    /**
     * 生成消息摘要
     * 用于通知显示，限制长度避免通知内容过长
     *
     * @param authorName 发布人名
     * @return 内容摘要
     *
     * @author: CYM-pai
     * @date: 2025/01/04 12:25
     */
    private String generateContentSummary(String authorName) {
        if (StringUtils.isNotBlank(authorName)) {
            return authorName +"发布了新动态";
        }
        return "";
    }

}
